<?php

/**
 *    网站地图更新控制器
 *
 *    @author    Garbin
 *    @usage    none
 */
class SitemapApp extends MallbaseApp
{

    function __construct()
    {
        $this->SitemapApp();
    }

    function SitemapApp()
    {
        parent::__construct();
        $this->_google_sitemmap_file = ROOT_PATH . '/sitemap.xml';
    }
    
    function index()
    {
        header("Location:".SITE_URL . '/sitemap.html');
        return;
    }

    function make_xml()
    {
        if(!isset($_GET['do']) || (isset($_GET['do']) && $_GET['do'] != "xmlnx")){
            header("Location:".SITE_URL . '/sitemap.xml');
            return;
        }
            
        if (!Conf::get('sitemap_enabled'))
        {
            return;
        }
        $from = empty($_GET['from']) ? 'google' : trim($_GET['from']);
        switch ($from)
        {
            case 'google':
                $this->_output_google_sitemap();
                break;
        }
    }

    function make_html()
    {
        if(!isset($_GET['do']) || (isset($_GET['do']) && $_GET['do'] != "htmlnx")){
            header("Location:".SITE_URL . '/sitemap.html');
            return;
        }
        
        $model_store = & m('store');
//        $stores = $model_store->findAll(array(
//            'fields' => 'store_id, store_name',
//            'conditions' => "tate=" . STORE_OPEN,
//        ));
        $sql = "select s.store_id, s.store_name from wl_store s left join wl_goods g on s.store_id=g.store_id where s.state=1 AND g.if_show=1 AND g.store_id is NOT NULL group by s.store_id";
        $stores = $model_store->getAll($sql);
        $gcategorys = $this->_list_gcategory();

        $acategorys = $this->_list_acategory();
        foreach ($acategorys as $key => $acategory)
        {
            if ($acategory['value'] == "帮助中心")
            {
                unset($acategorys);
                $acategorys = $acategory['children'];
                break;
            }
        }

        $this->assign('stores', $stores);
        $this->assign('gcategorys', $gcategorys);
        $this->assign('acategorys', $acategorys);

        $html = $this->return_display('sitemap.html');
        echo $html;
        file_put_contents("sitemap.html", $html);
    }

    /**
     *    输出Google sitemap
     *
     *    @author    Garbin
     *    @return    void
     */
    function _output_google_sitemap()
    {
        header("Content-type: application/xml");
        $xml = $this->_get_google_sitemap();
        echo $xml;
        file_put_contents("sitemap.xml", $xml);
    }

    /**
     *    获取Google sitemap
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_google_sitemap()
    {
//        $sitemap = "";
//        if ($this->_google_sitemap_expired())
//        {
            /* 已过期，重新生成 */

            /* 获取有更新的项目 */
//            $updated_items = $this->_get_updated_items($this->_get_google_sitemap_lastupdate());
            $updated_items = $this->_get_updated_items();

            /* 重建sitemap */
            $sitemap = $this->_build_google_sitemap($updated_items);

            /* 写入文件 */
            $this->_write_google_sitemap($sitemap);
//        }
//        else
//        {
//            /* 直接返回旧的sitemap */
//            $sitemap = file_get_contents($this->_google_sitemmap_file);
//        }

        return $sitemap;
    }

    /**
     *    判断Google sitemap是否过期
     *
     *    @author    Garbin
     *    @return    boolean
     */
    function _google_sitemap_expired()
    {
        if (!is_file($this->_google_sitemmap_file))
        {
            return true;
        }
        $frequency = Conf::get('sitemap_frequency') * 3600;
        $filemtime = $this->_get_google_sitemap_lastupdate();

        return (time() >= $filemtime + $frequency);
    }

    /**
     *    获取上次更新日期
     *
     *    @author    Garbin
     *    @return    int
     */
    function _get_google_sitemap_lastupdate()
    {
        return is_file($this->_google_sitemmap_file) ? filemtime($this->_google_sitemmap_file) : 0;
    }

    /**
     *    获取已更新的项目
     *
     *    @author    Garbin
     *    @return    array
     */
    function _get_updated_items($timeline = 0)
    {
        $timeline && $timeline -= date('Z');
        $limit = 5000;
        $result = array();
        /* 更新的店铺 */
        $model_store = & m('store');
        $sql = "select s.store_id from wl_store s left join wl_goods g on s.store_id=g.store_id where s.state=1 AND g.if_show=1 AND g.store_id is NOT NULL group by s.store_id";
        $updated_store = $model_store->getAll($sql);
//        $updated_store = $model_store->find(array(
//            'fields' => 'store_id',
//            'conditions' => "state=" . STORE_OPEN,
//            'limit' => "0, {$limit}",
//        ));

        if (!empty($updated_store))
        {
            foreach ($updated_store as $_store_id => $_v)
            {
                $result[] = array(
                    'url' => SITE_URL . '/store/' . $_v['store_id'] . ".html",
                    'lastmod' => date("Y-m-d"),
                    'changefreq' => 'daily',
                    'priority' => '0.8',
                );
            }
        }

        /* 分类 */
        $model_gcategory = & bm('gcategory');
        $gcategories = $model_gcategory->get_list(-1, true);
        if (!empty($gcategories))
        {
            foreach ($gcategories as $gcategory)
            {
                $result[] = array(
                    'url' => SITE_URL . '/search/cate_id/' . $gcategory['cate_id'] . '.html',
                    'lastmod' => date("Y-m-d"),
                    'changefreq' => 'daily',
                    'priority' => $gcategory['parent_id'] ? '0.8' : '1',
                );
            }
        }

        /* 更新的文章分类 */
        $acategory_mod = & m('acategory');
        $acategories = $acategory_mod->get_list(-1);
        if (!empty($acategories))
        {
            foreach ($acategories as $acategory)
            {
                $result[] = array(
                    'url' => SITE_URL . '/article/category/' . $acategory['cate_id'] . ".html",
                    'lastmod' => date("Y-m-d"),
                    'changefreq' => 'daily',
                    'priority' => '0.8',
                );
            }
        }

        /* 更新的文章 */
        $model_article = & m('article');
        $updated_article = $model_article->find(array(
            'fields' => 'article_id, add_time',
            'conditions' => "if_show=1",
            'limit' => "0, {$limit}",
        ));
        if (!empty($updated_article))
        {
            foreach ($updated_article as $_article_id => $_v)
            {
                $result[] = array(
                    'url' => SITE_URL . '/article/' . $_article_id . ".html",
                    'lastmod' => date("Y-m-d"),
                    'changefreq' => 'daily',
                    'priority' => '0.8',
                );
            }
        }

        return $result;
    }

    /**
     *    生成Google sitemap
     *
     *    @author    Garbin
     *    @param     array $items
     *    @return    string
     */
    function _build_google_sitemap($items)
    {
        $sitemap = "<\x3Fxml version=\"1.0\" encoding=\"UTF-8\"\x3F><\x3Fxml-stylesheet type=\"text/xsl\" href=\"" . SITE_URL . "/data/sitemap.xsl\"\x3F>
                   \n\t<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">";
        $sitemap .= "    <url>\r\n        <loc>" . htmlentities(SITE_URL, ENT_QUOTES) . "</loc>\r\n        <lastmod>" . date('Y-m-d', gmtime()) . "</lastmod>\r\n        <changefreq>always</changefreq>\r\n        <priority>1</priority>\r\n    </url>";
        if (!empty($items))
        {
            foreach ($items as $item)
            {
                $sitemap .= "\r\n    <url>\r\n        <loc>" . htmlentities($item['url'], ENT_QUOTES) . "</loc>\r\n        <lastmod>{$item['lastmod']}</lastmod>\r\n        <changefreq>{$item['changefreq']}</changefreq>\r\n        <priority>{$item['priority']}</priority>\r\n    </url>";
            }
        }
        $sitemap .= "\r\n</urlset>";

        return $sitemap;
    }

    /**
     *    写入Google sitemap文件
     *
     *    @author    Garbin
     *    @param     string $sitemap
     *    @return    void
     */
    function _write_google_sitemap($sitemap)
    {
        file_put_contents($this->_google_sitemmap_file, $sitemap);
    }

    private function _list_gcategory()
    {
        $model_gcategory = & bm('gcategory');
        $gcategories = $model_gcategory->get_list(-1, true);

        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
        $data = $tree->getArrayList(0);

        return $data;
    }

    private function _list_acategory()
    {
        $acategory_mod = & m('acategory');
        $acategories = $acategory_mod->get_list(-1);

        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($acategories, 'cate_id', 'parent_id', 'cate_name');
        $data = $tree->getArrayList(0);

        return $data;
    }

}

?>
